package com.example.sps.service.Impl;

import com.example.sps.commons.Constants;
import com.example.sps.commons.R;
import com.example.sps.commons.ServiceCode;
import com.example.sps.commons.ServiceException;
import com.example.sps.pojo.dto.*;
import com.example.sps.pojo.vo.*;
import com.example.sps.utils.AliossUtils;
import com.example.sps.utils.JWTUtils;
import com.example.sps.utils.MD5Utils;
import com.example.sps.mapper.EmployeeMapper;
import com.example.sps.pojo.entity.Employee;
import com.example.sps.service.EmployeeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @ProjectName: Sps
 * @Titile: EmployeeServiceImpl
 * @Author: nency
 * @Description: TODO
 */
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private AliossUtils aliossUtils;

    @Override
    public EmpLoginVO login(EmpLoginDTO empLoginDTO) {
        Employee emp = employeeMapper.getByPhone(empLoginDTO.getPhone());
        if(emp == null || emp.getId()==null){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"该手机号未注册");
        }
        if(emp.getDisabled()==Constants.DISABLED){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"该员工已经离职");
        }
        if(emp.getStatus()==Constants.LOCKED){
            throw new ServiceException(ServiceCode.ERROR_ACCOUNT_LOCK,"该员工被禁用");
        }
        String password = MD5Utils.enctype(empLoginDTO.getPassword(), emp.getSalt(), Constants.HASH_TIME);
        if(!password.equals(emp.getPassword())){
            throw new ServiceException(ServiceCode.ERROR_LOGIN,"密码错误");
        }
        EmpToken empToken = new EmpToken();
        empToken.setId(emp.getId());
        empToken.setPhone(emp.getPhone());
        String token = JWTUtils.generateToken(empToken);
        EmpLoginVO empLoginVO = new EmpLoginVO();
        empLoginVO.setId(emp.getId());
        empLoginVO.setEmpName(emp.getEmpName());
        empLoginVO.setAvatar(emp.getAvatar());
        empLoginVO.setToken(token);
        return empLoginVO;
    }

    @Override
    public R<EmpInfoVO> info(EmpToken empToken) {
        EmpInfoVO empInfoVO = employeeMapper.getById(empToken.getId());
        if(empInfoVO == null){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"未找到信息");
        }
        return R.ok("ok",empInfoVO);
    }

    @Override
    @Transactional
    public void updateEmpInfo(EmpInfoUpdateDTO empInfoUpdateDTO, EmpToken empToken) {
//        String originalFilename = empInfoUpdateDTO.getAvatar().getOriginalFilename();
//        String extend = originalFilename.substring(originalFilename.lastIndexOf("."));
//        String objectName = UUID.randomUUID().toString() + extend;
//        String filePath = null;
//        try {
//            filePath = aliossUtils.upload(empInfoUpdateDTO.getAvatar().getBytes(), objectName);
//        } catch (IOException e) {
//            log.info("文件上传失败，{}",e);
//            throw new ServiceException(ServiceCode.ERROR_UPLOAD,"文件上传失败");
//        }
        String filePath = null;
        try {
            filePath = aliossUtils.upload(empInfoUpdateDTO.getAvatar().getBytes(), empInfoUpdateDTO.getAvatar());
        } catch (IOException e) {
            log.info("文件上传失败，{}",e);
            throw new ServiceException(ServiceCode.ERROR_UPLOAD,"文件上传失败");
        }
        Employee employee = new Employee();
        employee.setEmpName(empInfoUpdateDTO.getEmpName());
        employee.setPhone(empInfoUpdateDTO.getPhone());
        employee.setAvatar(filePath);
        employee.setId(empToken.getId());
        employee.setModifyEmpId(empToken.getId());
        employeeMapper.updateEmpInfo(employee);
    }

    @Override
    public PageVO page(EmpPageQueryDTO empPageQueryDTO) {
        PageHelper.startPage(empPageQueryDTO.getPage(),empPageQueryDTO.getPageSize());
        Page<EmpVO> page = employeeMapper.pageQuery(empPageQueryDTO);
        return new PageVO(page.getTotal(),page.getResult(),page.getPageNum(),page.getPages());
    }

    @Override
    public R<Void> updatePwd(UpdatePwdDTO updatePwdDTO, EmpToken empToken) {
        if(!updatePwdDTO.getNewPwd().equals(updatePwdDTO.getRePwd())){
            throw new ServiceException(ServiceCode.ERROR,"确认密码和新密码不一致!");
        }
        Employee employee = employeeMapper.getByPhone(empToken.getPhone());
        String oldPassword = MD5Utils.enctype(updatePwdDTO.getOldPwd(), employee.getSalt(), Constants.HASH_TIME);
        if(!oldPassword.equals(employee.getPassword())){
            throw new ServiceException(ServiceCode.ERROR,"旧密码不正确！");
        }
        String newPassword = MD5Utils.enctype(updatePwdDTO.getNewPwd(), employee.getSalt(), Constants.HASH_TIME);
        if(newPassword.equals(employee.getPassword())){
            throw new ServiceException(ServiceCode.ERROR,"新密码与旧密码一致！");
        }
        String salt = UUID.randomUUID().toString().replace("-", "");
        newPassword = MD5Utils.enctype(updatePwdDTO.getNewPwd(), salt, Constants.HASH_TIME);
        employee.setSalt(salt);
        employee.setPassword(newPassword);
        employee.setModifyEmpId(empToken.getId());
        employee.setModifyTime(LocalDateTime.now());
        employeeMapper.updatePwd(employee);
        return R.ok("修改成功");
    }

    @Override
    public void updateStatus(EmpStatusDTO empStatusDTO, EmpToken empToken) {
        if(empStatusDTO.getEmpId().equals(empToken.getId())){
            throw new ServiceException(ServiceCode.ERROR,"不能修改自己的状态");
        }
        Employee employee = new Employee();
        employee.setId(empStatusDTO.getEmpId());
        employee.setStatus(empStatusDTO.getStatus());
        employee.setModifyEmpId(empToken.getId());
        employee.setModifyTime(LocalDateTime.now());
        employeeMapper.updateStatus(employee);
    }

    @Override
    public void deleteEmp(Integer empId, EmpToken empToken) {
        if(empId.equals(empToken.getId())){
            throw new ServiceException(ServiceCode.ERROR,"'员工不能删除自己！");
        }
        Employee employee = new Employee();
        employee.setId(empId);
        employee.setModifyEmpId(empToken.getId());
        employee.setModifyTime(LocalDateTime.now());
        employeeMapper.updateDisable(employee);
    }

    @Override
    public void addEmp(EmpDTO empDTO, EmpToken empToken) {
        MultipartFile avatar = empDTO.getAvatar();
        String filePath = null;
        if(avatar!=null){
            try {
                filePath = aliossUtils.upload(avatar.getBytes(), avatar);
            } catch (IOException e) {
                log.info("文件上传失败，{}",e);
                throw new ServiceException(ServiceCode.ERROR_UPLOAD,"文件上传失败");
            }
        }
        Employee employee = employeeMapper.getByPhone(empDTO.getPhone());
        if(employee!=null){
            throw new ServiceException(ServiceCode.ERROR,"手机号已经注册");
        }
        String salt = UUID.randomUUID().toString().replace("-", "");
        String password = MD5Utils.enctype(empDTO.getPassword(), salt, Constants.HASH_TIME);
        employee = new Employee();
        employee.setAvatar(filePath);
        employee.setPhone(empDTO.getPhone());
        employee.setEmpName(empDTO.getEmpName());
        employee.setSalt(salt);
        employee.setPassword(password);
        employee.setRoleId(empDTO.getRoleId());
        employee.setModifyEmpId(empToken.getId());
        employee.setModifyTime(LocalDateTime.now());
        employee.setStatus(empDTO.getStatus());
        employee.setRemark(empDTO.getRemark());
        employee.setDisabled(Constants.UN_DISABLED);
        employeeMapper.insert(employee);
    }

    @Override
    public EmpUpdateVO getByEmpId(Integer empId) {
        EmpUpdateVO empUpdateVO = employeeMapper.getByEmpId(empId);
        if(empUpdateVO==null){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"没有该员工的信息");
        }
        return empUpdateVO;
    }

    @Override
    public void editEmp(EmpUpdateDTO empUpdateDTO, EmpToken empToken) {
        MultipartFile avatar = empUpdateDTO.getAvatar();
        String filePath = null;
        if(avatar!=null){
            try {
                filePath = aliossUtils.upload(avatar.getBytes(), avatar);
            } catch (IOException e) {
                log.info("文件上传失败，{}",e);
                throw new ServiceException(ServiceCode.ERROR_UPLOAD,"文件上传失败");
            }
        }
        Employee employee = new Employee();
        employee.setEmpName(empUpdateDTO.getEmpName());
        employee.setId(empUpdateDTO.getEmpId());
        Employee emp = employeeMapper.getByPhone(empUpdateDTO.getPhone());
        if(emp!=null && emp.getId()!= empUpdateDTO.getEmpId()){
            throw new ServiceException(ServiceCode.ERROR,"手机号已经被使用");
        }
        employee.setPhone(empUpdateDTO.getPhone());
        String password = empUpdateDTO.getPassword();
        if(password!=null &&(password.length()>12)||password.length()<6){
            throw new ServiceException(ServiceCode.ERROR,"密码必须6-12位");
        }
        if(password!=null){
            String salt = UUID.randomUUID().toString().replace("-", "");
            employee.setSalt(salt);
            password = MD5Utils.enctype(password, salt, Constants.HASH_TIME);
            employee.setPassword(password);
        }
        employee.setRemark(empUpdateDTO.getRemark());
        employee.setRoleId(empUpdateDTO.getRoleId());
        employee.setStatus(empUpdateDTO.getStatus());
        employee.setAvatar(filePath);
        employee.setModifyEmpId(empToken.getId());
        employee.setModifyTime(LocalDateTime.now());
        employeeMapper.editEmp(employee);
    }
}
